<template>
  <view class="login-container">
    <!-- 提示登录的图标 -->
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <!-- 登录按钮 -->
    <button type="primary" class="btn-login" @click="login">微信登录</button>
    <!-- 登录提示 -->
    <view class="tips-text" @click="goToAccountLogin">账号登录</view>

    <!-- 登录授权底部弹出层 -->
    <uni-popup ref="popup" type="bottom" is-mask-click="true">
      <view class="user-form">
        <form @submit="formSubmit">
          <view class="prompt">申请获取您的头像、昵称</view>

          <view class="get_user">
            <view class="user-view">头像：
              <button class="avatar_btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="user-img" :src="avatarUrl" mode="aspectFill" />
              </button>
            </view>
            <view class="user-view">昵称：
              <input class="user-name" name="nickName" type="nickname" placeholder="请输入昵称" />
            </view>
          </view>

          <view class="popup-button">
            <button class="refuse-btn" form-type="reset" @click="closePopup">拒绝</button>
            <button class="allow-btn" form-type="submit" type="primary">允许</button>
          </view>
        </form>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  const defaultAvatarUrl =
    'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
  export default {
    name: "my-login",
    computed: {
      ...mapState('m_user', ['redirectInfo', 'userinfo']),
    },
    data() {
      return {
        avatarUrl: defaultAvatarUrl,
        userName: '',
        userToken: '',
        userInfo: {
          userID: '',
          userAvatar: '',
          userName: '',
          userGender: '',
          userLikeNumber: '',
          userWeight: '',
          userBMI: '',
          userPhoneNumber: '',
          userRegion: '',
          userEmail: '',
          userBgImg: '',
          userAddress: '',
        }
      };
    },
    methods: {
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo', 'updateUserAvatar', 'updateUserClockInList', 'updateUserPlanList', 'updateUserRecordList', 'updateUserVideoList', 'updateUserArticleList', 'updateUserTrendList', 'updateUserLikeTrendList']),
      ...mapMutations('m_music', ['setUserMusicList']),
      ...mapMutations('m_cart', ['updateUserCartList']),
      // 登录
      login() {
        this.getUserProfile()
      },
      // 申请获取用户信息，打开底部弹出层
      openPopup() {
        this.$refs.popup.open()
      },
      // popup弹窗点击"允许"按钮触发提交事件函数
      formSubmit(e) {
        let nickName = e.detail.value.nickName
        if (this.avatarUrl === defaultAvatarUrl) {
          return uni.$showMsg('请选择头像！')
        } else if (!nickName) {
          return uni.$showMsg('请输入昵称！')
        } else {
          this.userInfo.userAvatar = this.avatarUrl
          this.userInfo.userName = e.detail.value.nickName
          this.userName = e.detail.value.nickName
          this.createNewUser()
          this.$refs.popup.close()
          return uni.$showMsg('登录成功')
        }
      },
      // popup弹窗点击"拒绝"按钮关闭popup弹窗
      closePopup() {
        this.$refs.popup.close()
        this.avatarUrl = defaultAvatarUrl
      },
      // 获取用户头像
      onChooseAvatar(e) {
        console.log(e.detail)
        const {
          avatarUrl
        } = e.detail
        this.avatarUrl = avatarUrl
      },
      async getUserProfile() {
        try {
          const [err, res] = await uni.getUserProfile({
            desc: '你的授权信息'
          }).catch(err => err)
          console.log('用户授权返回数据==', res)
          if (res.errMsg !== 'getUserProfile:ok') return uni.$showMsg('您取消了登录授权')
          // 获取token并调用其他函数
          this.getToken(res)
        } catch (error) {
          console.log(error)
        }
      },

      // 获取授权成功后的 Token 字符串的处理函数
      async getToken(info) {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
        // 准备参数
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        const {
          data: loginResult
        } = await uni.$http.post('/api/wxLogin', query)
        console.log('后端返回的登录数据loginResult', loginResult)
        if (loginResult.meta.status === 404) {
          this.openPopup()
          return
        } else if (loginResult.meta.status === 200) {
          // 将 token 保存到 vuex 中
          console.log(loginResult.message.token)
          console.log(loginResult.message.userInfo)
          this.userInfo = loginResult.message.userInfo
          this.updateToken(loginResult.message.token)
          //获取用户信息后更新userInfo
          this.updateUserInfo(loginResult.message.userInfo)
          // 获取用户所有的信息资料
          this.getUserInformation()
          return uni.$showMsg('登录成功！')
        }
      },
      // 创建新用户
      async createNewUser() {
        const [err, res] = await uni.login().catch(err => err)
        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
        // 准备参数
        const query = {
          code: res.code,
          avatarUrl: this.avatarUrl,
          userName: this.userName,
        }
        const {
          data: createResult
        } = await uni.$http.post('/api/wxCreateNewUser', query)
        if (createResult.meta.status === 404) {
          uni.$showMsg('登录失败！')
          return
        } else if (createResult.meta.status === 200) {
          // 将 token 保存到 vuex 中
          console.log(createResult.message.token)
          console.log(createResult.message.userInfo)
          this.userInfo = createResult.message.userInfo
          this.uploadAvatarToServer()
          this.updateToken(createResult.message.token)
          //获取用户信息后更新userInfo
          this.updateUserInfo(createResult.message.userInfo)
          uni.$showMsg('登录成功！')
        }
        
      },
      // 获取用户所有信息资料
      async getUserInformation() {
        var token = uni.getStorageSync('token')
        // 调用获取用户所有信息资料
        const {
          data: res
        } = await uni.$http.get('/api/get/userInformation?token=' + token)
        console.log(res.message)
        this.updateUserClockInList(res.message.clockinList)
        this.updateUserPlanList(res.message.planList)
        this.updateUserRecordList(res.message.recordList)
        this.updateUserVideoList(res.message.videoList)
        this.updateUserArticleList(res.message.articleList)
        this.updateUserCartList(res.message.cartList)
        this.updateUserTrendList(res.message.trendList)
        this.updateUserLikeTrendList(res.message.likeTrendList)
        this.setUserMusicList(res.message.musicList)
      },
      // 上传头像到服务器中
      uploadAvatarToServer() {
        const userID = this.userInfo.userID
        console.log('上传头像userID', userID)
        console.log('上传头像')
        uni.uploadFile({
          filePath: this.avatarUrl,
          name: 'image',
          url: 'https://jeoz.top:3000/api/uploadAvatar?userID=' + userID,
          success: res => {
            const responseData = JSON.parse(res.data);
            const newAvatarUrl = responseData.message.newAvatarUrl;
            this.updateUserAvatar(newAvatarUrl)
            console.log('上传成功')
          }
        })
      },
      // 返回登录之前的页面
      navigateBack() {
        // redirectInfo 不为 null，并且导航方式为 switchTab
        if (this.redirectInfo && this.redirectInfo.openType === 'navigateTo') {
          uni.navigateTo({
            // 要导航到的页面地址
            url: this.redirectInfo.from,
            // 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
            complete: () => {
              this.updateRedirectInfo(null)
            }
          })
        }
      },
      // 跳转到登录页面事件
      goToAccountLogin() {
        uni.navigateTo({
          url: '../../subpkg/account_login/account_login'
        })
      },
    }
  }
</script>

<style lang="scss">
  page {
    background-color: white;
  }

  .login-container {
    // 登录盒子的样式
    height: 750rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
    position: relative;

    // 绘制登录盒子底部的半椭圆造型
    &::after {
      content: '';
      display: block;
      position: absolute;
      width: 100%;
      height: 40px;
      bottom: 0;
      left: 0;
      background-color: white;
      border-radius: 100%;
      transform: translateY(50%); // 向下移动自身50%的距离
    }

    .btn-login {
      //登录按钮的样式
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
      background-color: #fba007;
    }

    .tips-text {
      //按钮下方提示消息的样式
      font-size: 12px;
      color: gray;
    }

    // uni-popup
    .user-form {
      height: 190px;
      background: white;
      border-top-left-radius: 30rpx;
      border-top-right-radius: 30rpx;
      padding-top: 18px;

      .prompt {
        // border: 1rpx solid black;
        font-size: 30rpx;
        font-weight: bolder;
        margin-left: 30rpx;
      }

      .get_user {
        .user-view {
          // border: 1rpx solid black;
          height: 100rpx;
          display: flex;
          align-items: center;
          color: gray;
          font-size: 28rpx;
          border-bottom: 1px solid #ddd;
          margin-left: 30rpx;
          margin-right: 30rpx;

          .avatar_btn {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            background-color: transparent;
            padding: 0;
            margin-right: 20rpx;
            line-height: 1.3;
          }

          ::after {
            border: none;
            border-radius: 0;
          }

          .user-img {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
          }

          .user-name {
            flex: 1;
            text-align: right;
            font-size: 28rpx;
            color: black;
            // border: 1rpx solid gray;
            border-radius: 10rpx;
            padding-right: 24rpx;
          }
        }
      }

      .popup-button {
        width: 440rpx;
        margin: 15px auto;
        display: flex;


        // border: 1rpx solid black; 
        /* padding: 0; */
        .refuse-btn {
          width: 200rpx;
          height: 70rpx;
          line-height: 70rpx;
          margin: 0;
          /* align-items: center;
              justify-content: center; */
          color: black;
          font-size: 28rpx;
          border-radius: 100px;
          background-color: #eee;
        }

        ::after {
          border: none;
        }

        .allow-btn {
          width: 200rpx;
          height: 70rpx;
          line-height: 70rpx;
          font-size: 28rpx;
          /* align-items: center; */
          /* justify-content: center; */
          /* display: flex; */
          margin-left: 40rpx;
          border-radius: 100px;
          background-color: #fba007;
        }
      }
    }

  }
</style>